package com.bestcem.xm.member.controller;

import cn.hutool.core.bean.BeanUtil;
import com.bestcem.xm.common.core.constant.RegTypes;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.member.controller.param.HttpUpdateSyncRuleParam;
import com.bestcem.xm.member.controller.vo.SyncRuleVO;
import com.bestcem.xm.member.controller.vo.UpdateSyncRuleVO;
import com.bestcem.xm.member.grpc.service.param.syncrule.CreateSyncRuleParam;
import com.bestcem.xm.member.grpc.service.param.syncrule.GetSyncRuleParam;
import com.bestcem.xm.member.grpc.service.param.syncrule.UpdateSyncRuleParam;
import com.bestcem.xm.member.service.SyncRuleService;
import com.bestcem.xm.member.service.dto.SyncRuleDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.List;
import java.util.Map;

/**
 * @author ming.xue <ming.xue@idiaoyan.com>
 * @desc 同步规则控制器
 * @date 2021-08-16
 */
@Slf4j
@RestController
@RequestMapping("/member")
public class SyncRuleController {
    /**
     * 同步规则服务
     */
    @Autowired
    private SyncRuleService syncRuleService;

    /**
     * 获取同步规则
     *
     * @param memberType
     * @return
     */
    @GetMapping("/syncrules")
    public XmResultJson<SyncRuleVO> getSyncRule(
            @RequestParam(name = "attribute", required = false) Integer memberType,
            HttpServletRequest request) {

        
        String orgId = SecurityContextHolder.getOrgId();
        GetSyncRuleParam param = new GetSyncRuleParam();
        param.setMemberType(memberType);
        param.setOrgId(orgId);
        ServiceResult<SyncRuleDTO> result = syncRuleService.getSyncRule(param);
        if (result.isSuccess()) {
            SyncRuleDTO data = result.getData();
            SyncRuleVO syncRuleVO = new SyncRuleVO();
            BeanUtil.copyProperties(data, syncRuleVO);
            return XmResultJson.success(syncRuleVO);
        } else {
            log.error("同步规则获取失败", result.getMsg());
            return XmResultJson.fail(-1, "Request handler no return value.");
        }
    }

    /**
     * 创建同步规则
     *
     * @param ruleParam
     * @return
     */
    @PostMapping("/syncrules")
    public XmResultJson<UpdateSyncRuleVO> getSyncRule(
            @RequestBody HttpUpdateSyncRuleParam ruleParam,
            HttpServletRequest request) {

        
        String orgId = SecurityContextHolder.getOrgId();
        
         String userId = SecurityContextHolder.getUserId();
        if (log.isInfoEnabled()) {
            log.info("orgId: {}", orgId);
            log.info("userId: {}", userId);
        }
        CreateSyncRuleParam param = new CreateSyncRuleParam();
        param.setMemberType(ruleParam.getMemberType());
        param.setOrgId(orgId);
        param.setQueryFields(ruleParam.getQueryFields());
        param.setUpdateFields(ruleParam.getUpdateFields());
        param.setSyncType(ruleParam.getType());
        ServiceResult<String> syncRule = syncRuleService.createSyncRule(param);
        if (syncRule.isSuccess()) {
            UpdateSyncRuleVO vo = new UpdateSyncRuleVO();
            vo.setId(syncRule.getData());
            return XmResultJson.success(vo);
        } else {
            log.error("同步规则创建失败", syncRule.getMsg());
            return XmResultJson.fail(-1, "Request handler no return value.");
        }
    }

    /**
     * 修改同步规则
     *
     * @param id
     * @param ruleParam
     * @param request
     * @return
     */
    @PutMapping("/syncrules/{id}")
    public XmResultJson<UpdateSyncRuleVO> updateSyncRule(
            @PathVariable String id,
            @RequestBody HttpUpdateSyncRuleParam ruleParam,
            HttpServletRequest request) {

        
        String orgId = SecurityContextHolder.getOrgId();
        
         String userId = SecurityContextHolder.getUserId();
        if (log.isInfoEnabled()) {
            log.info("orgId: {}", orgId);
            log.info("userId: {}", userId);
        }
        UpdateSyncRuleParam param = new UpdateSyncRuleParam();
        param.setId(id);
        param.setQueryFields(ruleParam.getQueryFields());
        param.setUpdateFields(ruleParam.getUpdateFields());
        param.setSyncType(ruleParam.getType());
        ServiceResult<SyncRuleDTO> result = syncRuleService.updateSyncRule(param);
        if (result.isSuccess()) {
            UpdateSyncRuleVO vo = new UpdateSyncRuleVO();
            vo.setId(result.getData().getId());
            return XmResultJson.success(vo);
        } else {
            return XmResultJson.fail(-1, result.getMsg());
        }
    }

    /**
     * 获取同步规则默认字段列表
     *
     * @param memberType
     */
    @GetMapping("/syncrules_default")
    public XmResultJson<Map<String, List<String[]>>> listDefaultSyncRuleFields(
            @RequestParam(name = "attribute", required = true) Integer memberType) {
        ServiceResult<Map<String, List<String[]>>> result = syncRuleService.listDefaultSyncRuleFields(memberType);
        return XmResultJson.handleServiceResult(result);
    }

    /**
     * 重置同步规则
     *
     * @param id
     * @return
     */
    @PutMapping("/syncrules_default/{id}")
    public XmResultJson<SyncRuleDTO> restoreSyncRule(
            @PathVariable(name = "id")
            @NotNull(message = "同步规则标识不能为空")
            @Pattern(regexp = RegTypes.OBJECT_ID, message = "同步规则标识格式错误") String id) {
        ServiceResult<SyncRuleDTO> result = syncRuleService.restoreSyncRule(id);
        return XmResultJson.handleServiceResult(result);
    }

}
